//
//  ZLUserAcount.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/22.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import UIKit

fileprivate let accountFile = "useraccount.json"
//用户账户信息
class ZLUserAcount: NSObject {

    var access_token: String?
    var uid: String?
    var screen_name: String?
    var avatar_large: String?
    var expires_in: TimeInterval = 0.0{
        
        didSet {
            
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    var remind_in: TimeInterval = 0.0
    
    var expiresDate: Date?
    
    override var description: String{
        
        return yy_modelDescription()
    }
    override init() {
        
        super.init()
        
        
        guard let path = accountFile.hm_appendDocumentDir,let data = NSData(contentsOfFile: path),let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) else{
            
            
            return
        }
        yy_modelSet(with: dict as! [AnyHashable : Any])
        
        print("从沙河取到的用户信息\(self)")
        //判断token是否过期
        //测试过期日期
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if  expiresDate?.compare(Date()) != .orderedDescending{
            
            print("登录过期")
            access_token = nil
            
            uid = nil
            //删除账户文件
            _ = try? FileManager.default.removeItem(atPath: path)
        }
        
    }
    /**
     1.偏好设置
     2.沙盒
     3.数据库
     4.钥匙串访问
     */
    func savaAccount() {
        
        //模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict , options: []),let filepath = accountFile.hm_appendDocumentDir else{
            
            return
        }
        
        print("\(filepath)")
        (data as NSData).write(toFile: filepath, atomically: true)
        
    }
}
